package com.lipuwater.agent.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ismartlib.utils.NetUtils;
import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.bean.user.PersonnelInfoBean;
import com.lipuwater.agent.http.bean.user.RoleConfig;
import com.lipuwater.agent.http.bean.user.RolesBean;
import com.lipuwater.agent.http.bean.user.RolesListBean;
import com.lipuwater.agent.utils.MapToBeanUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mehdi.sakout.fancybuttons.FancyButton;
import okhttp3.Call;

public class PersonnelEditOrAdd extends BaseLayoutActivity implements TextWatcher {

    @Bind(R.id.edit_account)
    EditText editAccount;
    @Bind(R.id.edit_username)
    EditText editUsername;
    @Bind(R.id.edit_password)
    EditText editPassword;
    @Bind(R.id.edit_confirm_password)
    EditText editConfirmPassword;
    @Bind(R.id.layout_roles)
    LinearLayout layoutRoles;
    @Bind(R.id.btn_confirm)
    FancyButton btnConfirm;


    private PersonnelInfoBean mPersonnelInfo;
    private String func = "add";
    private int personnelId, rolesId;
    private String mRolesType = "";//角色类型

    private RolesListBean mRolesList;

    private boolean updatePassWord = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_personnel_edit_or_add);
        ButterKnife.bind(this);
        toolbar.setBackgroundResource(R.drawable.img_title_bar);
        toolbarTitle.setTextColor(Color.parseColor("#ffffff"));
        func = getIntent().getStringExtra("func");
        if (func.equals("edit")) {
            initTitle(R.drawable.icon_aleft_white, "人员编辑");
        } else if (func.equals("add")) {
            initTitle(R.drawable.icon_aleft_white, "新增人员");
        }
        showLoading();
        getRoles();
    }

    private void getRoles() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        ApiRequestsBasis.getRoles(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    mRolesList = (RolesListBean) MapToBeanUtil.toJavaBean(result.getParams(), RolesListBean.class);
                    initView();
                    hideEmptyLayout();
                } else {
                    showNoNetWork();
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                showNoNetWork();
                if (!NetUtils.isConnected(PersonnelEditOrAdd.this)) {
                    Toast(getString(R.string.network_fails));
                } else {
                    Toast(getString(R.string.service_error));
                }
            }
        });
    }

    private void initView() {
        if (func.equals("edit")) {
            mPersonnelInfo = (PersonnelInfoBean) getIntent().getSerializableExtra("userInfo");
            if (mPersonnelInfo != null) {
                editAccount.setText(mPersonnelInfo.getAccount());
                editUsername.setText(mPersonnelInfo.getUsername());
                personnelId = mPersonnelInfo.getId();
                rolesId = mPersonnelInfo.getRole();
                mRolesType = mPersonnelInfo.getEnname();
            }
        } else if (func.equals("add")) {
            editPassword.setText("");
            editConfirmPassword.setText("");
        }
        editPassword.addTextChangedListener(this);
        editConfirmPassword.addTextChangedListener(this);
        //rolesList.getList().get(0)!=null防止服务器返回list：[null]的情况
        if (mRolesList != null && mRolesList.getList() != null && mRolesList.getList().size() > 0 && mRolesList.getList().get(0) != null) {
            final List<RolesBean> rolesList = mRolesList.getList();
            for (int i = 0; i < rolesList.size(); i++) {
                View view = LayoutInflater.from(this).inflate(R.layout.item_roles, null);
                TextView textView = (TextView) view.findViewById(R.id.text_name);
                textView.setText(rolesList.get(i).getName());
                //如果当前用户不是主管并且当前选项是主管的话就隐藏掉主管选项
                if (!mRolesType.equals(RoleConfig.MANAGER) && rolesList.get(i).getEnname().equals(RoleConfig.MANAGER)) {
                    view.setVisibility(View.GONE);
                } else if (rolesId == rolesList.get(i).getId()) {
                    view.findViewById(R.id.image_bel).setVisibility(View.VISIBLE);
                }
                final int position = i;
                //如果不是主管才可以点击选择
                if (!mRolesType.equals(RoleConfig.MANAGER)) {
                    view.findViewById(R.id.layout_item).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //时间关系，暂时先这么写了，后续再改
                            for (int i = 0; i < layoutRoles.getChildCount(); i++) {
                                View view = layoutRoles.getChildAt(i);
                                view.findViewById(R.id.image_bel).setVisibility(View.GONE);
                            }
                            layoutRoles.getChildAt(position).findViewById(R.id.image_bel).setVisibility(View.VISIBLE);
                            rolesId = rolesList.get(position).getId();
                        }
                    });
                }
                layoutRoles.addView(view);
            }
        }
    }

    @OnClick(R.id.btn_confirm)
    public void onClick() {
        if (editAccount.getText().toString().equals("")) {
            Toast("请输入账号");
            return;
        }
        if (editUsername.getText().toString().equals("")) {
            Toast("请输入昵称");
            return;
        }
        if (editPassword.getText().toString().equals("") || editConfirmPassword.getText().toString().equals("")) {
            Toast("请输入密码");
            return;
        }
        if (!editPassword.getText().toString().equals(editConfirmPassword.getText().toString())) {
            Toast("两次密码输入不一样");
            return;
        }
        if (rolesId == 0) {
            Toast("请选择人员角色");
            return;
        }
        upDatePersonnel(personnelId, rolesId);
    }

    private void upDatePersonnel(int personnelId, int roleId) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("func", func);
        Map<String, Object> user = new HashMap<>();
        if (func.equals("edit")) {
            user.put("id", personnelId + "");
        }
        user.put("account", editAccount.getText().toString());
        user.put("username", editUsername.getText().toString());
        if (updatePassWord) {
            user.put("password", editPassword.getText().toString());
        }
        user.put("roleId", roleId + "");
        params.put("user", user);
        ApiRequestsBasis.upDatePersonnel(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    Toast("保存成功");
                    Intent intent = new Intent();
                    intent.putExtra("update", true);
                    setResult(101, intent);
                    finish();
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (!NetUtils.isConnected(PersonnelEditOrAdd.this)) {
                    Toast(getString(R.string.network_fails));
                } else {
                    Toast(getString(R.string.service_error));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        ApiRequestsBasis.cancelRequests(this);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        updatePassWord = true;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
